from socket import *
from PyQt5 import uic
from PyQt5.QtWidgets import QApplication

class client():
    def __init__(self):                                
        self.BUFLEN = 512                               
        self.dataSocket = socket(AF_INET, SOCK_STREAM)  # 实例化一个socket对象，指明协议
        self.link_flag = 0                              # 初始化连接标志位

        self.ui = uic.loadUi("ui/TCP.ui")
        self.ui.setWindowTitle("通信系统")

        self.ui.pushButton_link.clicked.connect(self.link)
        self.ui.pushButton_sent.clicked.connect(self.sent)
        self.ui.pushButton_renew.clicked.connect(self.renew)
        self.ui.pushButton_close.clicked.connect(self.close)

    def link(self):
        IP = self.ui.lineEdit_IP.text()                 # 获取地址和端口号
        PORT = self.ui.lineEdit_PROT.text()
        if IP and PORT:                                 
            self.ui.message.append("正在尝试连接···")
            self.dataSocket.connect((IP, int(PORT)))   
            self.link_flag = 1                          # 连接成功
            self.ui.message.append("服务端连接成功！")
            print('接受到服务端连接')
        else:
            self.ui.message.append("请输入正确的服务器IP与服务器PORT")

    def close(self):
        if self.link_flag == 1:
            self.link_flag = 0
            self.dataSocket.close()
            self.ui.message.append("服务端断开成功！")
            print('断开服务端连接')
        else:
            self.ui.message.append("服务器未连接！")

    def sent(self):
        if self.link_flag == 1:
            toSend = self.ui.send_message.toPlainText()         
            if toSend in ('','请输入内容！！'):                    
                self.ui.send_message.clear()                     
                self.ui.send_message.append("请输入内容！！")     
            else:
                self.dataSocket.send(toSend.encode())            
                recved = self.dataSocket.recv(self.BUFLEN)       # 等待接收服务端的消息（阻塞性，确认对方收到才继续）
                if not recved:                                   # 如果返回空bytes，表示对方关闭了连接
                    self.ui.message.append("服务端断开连接！")
                self.ui.message.append(recved.decode())          # 显示解码后接收到的信息
                print(recved.decode())                          
        else:
            self.ui.send_message.clear()
            self.ui.send_message.append("请连接服务器！！")

    def renew(self):
        self.ui.send_message.clear()                             # 清空输入框

if __name__ == '__main__':
    app = QApplication([])
    temp = client()
    temp.ui.show()
    app.exec_()